<template>
  <div class="controls">
    <input
      autocomplete="off"
      class="itxt"
      :value="currentValue"
      @blur="handleChange"
      @keyup.enter="handleChange"
    />
    <a :class="{ plus: true, disabled: currentValue === max }" @click="add">
      +
    </a>
    <a :class="{ mins: true, disabled: currentValue === min }" @click="count">
      -
    </a>
  </div>
</template>

<script>
export default {
  name: "InputNumber",
  props: {
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 10,
    },
    value: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      currentValue: this.value,
    };
  },
  methods: {
    handleChange(e) {
      this.currentValue = +e.target.value.trim();
    },
    add() {
      if (this.currentValue === this.max) return;
      this.currentValue++;
    },
    count() {
      if (this.currentValue === this.min) return;
      this.currentValue--;
    },
  },
  watch: {
    currentValue(newVal, oldVal) {
      // 对currentValue进行修正
      const { min, max } = this;
      let currentValue = newVal;

      // 4. 输入非数字内容，等于之前的值
      if (Number.isNaN(currentValue)) {
        currentValue = oldVal;
      }
      // 2. 输入小于最小值，等于最小值
      if (newVal < min) {
        currentValue = min;
      }
      // 3. 输入大于最大值，等于最大值
      if (newVal > max) {
        currentValue = max;
      }

      this.currentValue = currentValue;
      this.$emit("input", currentValue);
    },
  },
};
</script>

<style lang="less" scoped>
.controls {
  width: 48px;
  position: relative;
  float: left;
  margin-right: 15px;

  .itxt {
    width: 38px;
    height: 37px;
    border: 1px solid #ddd;
    color: #555;
    float: left;
    border-right: 0;
    text-align: center;
  }

  .plus,
  .mins {
    width: 15px;
    text-align: center;
    height: 17px;
    line-height: 17px;
    background: #f1f1f1;
    color: #666;
    position: absolute;
    right: -8px;
    border: 1px solid #ccc;
    &.disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }

  .mins {
    right: -8px;
    top: 19px;
    border-top: 0;
  }

  .plus {
    right: -8px;
  }
}
</style>
